import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
// 自动配置路由
import Pages from "vite-plugin-pages";
// gzip压缩
import viteCompression from "vite-plugin-compression";
// 页面setup设置名称
import VueSetupExtend from "vite-plugin-vue-setup-extend";
// import { createHtmlPlugin } from "vite-plugin-html";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import path from "path";
import fs from "fs";
// 多页打包定义入口
const inputs: { [propName: string]: string } = {};
const excludeFiles = [
  "components",
  "index.ts",
  "index.vue",
  "auto-imports.d.ts",
  "components.d.ts"
]; // 排除打包的多页文件
fs.readdirSync(path.resolve(__dirname, "src/views")).forEach(filename => {
  if (excludeFiles.includes(filename)) return;
  inputs[filename] = path.resolve(
    __dirname,
    filename == "index.html"
      ? `src/views/${filename}`
      : `src/views/${filename}/index.html`
  );
});

console.log(inputs, "  inputs ");

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, "");
  console.log(env, mode);
  if (mode == "production") {
    // 生产环境删除index.html
    delete inputs["index.html"];
    console.log(inputs);
  }

  const proxy: any = {};
  if (mode == "development") {
    for (const key in env) {
      if (
        Object.prototype.hasOwnProperty.call(env, key) &&
        key.includes("VITE_BASE_API")
      ) {
        proxy[env[key]] = {
          target: "http://xxx.xx.xxx.xx:xxxx/xxxx",
          secure: false,
          changeOrigin: true
          // rewrite: (path) => path.replace(/^\/local\//, ''),
        };
      }
    }
  }
  return {
    base: env.VITE_PUBLIC_PATH || "/",
    root: path.resolve(__dirname, "src/views/"), // '/'表示从src下开始查找
    envDir: path.resolve(__dirname), // 由于改了根目录 env改回项目根目录下
    publicDir: path.resolve(__dirname, "public"),
    plugins: [
      vue(),
      VueSetupExtend({ name: false }),
      // 注入模板数据
      // createHtmlPlugin({}),
      viteCompression({
        // 记录压缩文件及其压缩率。默认true
        verbose: true,
        // 是否禁用压缩，默认false
        disable: false,
        // 需要使用压缩前的最小文件大小，单位字节（byte） b，1b(字节)=8bit(比特), 1KB=1024B
        threshold: 10240, // 即10kb以上即会压缩
        // 压缩算法 可选 'gzip' | 'brotliCompress' | 'deflate' | 'deflateRaw'
        algorithm: "gzip",
        // 压缩后的文件格式
        ext: ".gz"
      }),
      AutoImport({
        resolvers: [VantResolver()]
      }),
      Components({
        resolvers: [VantResolver()]
      }),
      Pages({
        dirs: "",
        exclude: [
          "**/components/*.vue",
          "**/components/**/*.vue",
          "**/components/**/**/*.vue",
          "**/components/**/**/**/*.vue",
          "**/app.vue",
          "**/*.js",
          "**/*.html",
          "**/*.ts"
        ], // 排除在外的目录，即不将所有 components 目录下的 .vue 文件生成路由
        importMode: "async"
        // extendRoute(route, parent) {
        // console.log(route, ' route ');
        // if (route.path === '/') {
        //   // Index is unauthenticated.
        //   return route;
        // }

        // // Augment the route with meta that indicates that the route requires authentication.
        // return {
        //   ...route,
        //   meta: { ...route.meta, auth: true },
        // };
        // },
      })
    ],

    css: {
      devSourcemap: mode === "development"
    },

    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
        "~": path.resolve(__dirname, "src/components")
      }
    },

    server: {
      host: true,
      port: 8080,
      proxy
    },

    build: {
      outDir: path.resolve(__dirname, "dist"),
      minify: "terser", // 设置terserOptions项才生效
      emptyOutDir: true,
      terserOptions: {
        compress: {
          // drop_console: mode !== "development",
          // drop_debugger: mode !== "development"
        }
      },
      sourcemap: mode === "development",
      rollupOptions: {
        input: inputs,
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          compact: true,
          manualChunks(id) {
            // 静态资源分拆打包
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          }
        }
      }
    }
  };
});
